package com.atguigu.gulimall.member.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.LoginRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器，定义拦截规则
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    //把session中的用户信息存入全局线程中
    public static ThreadLocal<LoginRespVo> local = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if (match){
            return true;
        }

        Object loginUser = request.getSession().getAttribute(AuthServerConstant.USER_LOGIN_SESSION_NAME);
        if(loginUser == null){
            request.getSession().setAttribute("msg", "请先登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
        LoginRespVo member = (LoginRespVo)loginUser;
        local.set(member);
        return true;
    }
}
